/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.server.version.model;

import java.util.Calendar;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.version.Version;
import javax.jcr.version.VersionHistory;
import offset.nodes.Constants;

/**
 *
 * @author Walter L�tgenau
 */
public class VersionModel {
    Session session;

    public VersionModel(Session session) {
        this.session = session;
    }

    /**
     * Retrieve the frozen node representing the versioned child from the version repository.
     * 
     * @param versionedChild
     * @return FrozenNode
     */
    public Node getFrozenNode(Node versionedChild) throws RepositoryException {
        Node parentVersion = versionedChild.getParent().getParent();
        Calendar parentCreation = parentVersion.getProperty(Constants.JCR_CREATED).getDate();
        
        Node versionHistory = (VersionHistory) session.getNodeByUUID(versionedChild.getProperty(Constants.JCR_CHILD_VERSION_HISTORY).getString());
        Node version = versionHistory.getNode(Constants.JCR_ROOT_VERSION);
        Node previous = version;

        while (version.getProperty(Constants.JCR_CREATED).getDate().before(parentCreation)
                && version.hasProperty(Constants.JCR_SUCCESSORS)
                && version.getProperty(Constants.JCR_SUCCESSORS).getValues().length == 1) {
            Node successor = session.getNodeByUUID(version.getProperty(Constants.JCR_SUCCESSORS).getValues()[0].getString());
            if (!successor.getProperty(Constants.JCR_CREATED).getDate().before(parentCreation))
                break;
            version = successor;
        }

        return version.getNode(Constants.JCR_FROZEN_NODE);
    }
}
